package com.leesche.zcsp.node.app.v1.timer;

import com.leesche.zcsp.node.app.v1.constants.AppContants;
import com.leesche.zcsp.node.web.model.SysUserToken;
import com.leesche.zcsp.node.web.service.SysModuleService;
import com.leesche.zcsp.node.web.service.SysUserService;
import com.leesche.zcsp.node.web.service.SysUserTokenService;
import com.leesche.zcsp.node.web.service.impl.data.read.QuerySysUserTokenCondition;
import com.leesche.zcsp.node.web.vo.Principal;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * Created by dessnis yang  on 2016-12-05.
 */
@Component
@Lazy(value = false)
public class TokenCacheTimer {
    private final static Logger LOGGER = Logger.getLogger(TokenCacheTimer.class);
    /**用户token保存**/
    private static Map<String,SysUserToken> tokenMap=new HashMap<String,SysUserToken>();

    //保存用户状态
    private static Map<Long,Principal> principalMap=new HashMap<Long,Principal>();


    @Autowired
    private SysUserTokenService sysUserTokenService;

    @Autowired
    private SysModuleService sysModuleService;

    @Autowired
    private SysUserService sysUserService;

    /***
     * <p>加载所有有限期的内的token</p>
     */
   @Scheduled(fixedRate = 1000 * 60 * 60 * 2)
    public void  loadAllToken(){
        LOGGER.info("加载所有有效期内的Token......");
        //加载所有有效期内的token
        QuerySysUserTokenCondition condition=new QuerySysUserTokenCondition();
        condition.setOuttime(new Date());
        List<SysUserToken> lists=  sysUserTokenService.findUserInfoListDtoByCondition(condition);
        for(SysUserToken newToken:lists){
            SysUserToken oldToken=tokenMap.get(newToken.getToken());
            if(oldToken==null||(!oldToken.equals(newToken))){
                tokenMap.put(newToken.getToken(),newToken);
                continue;
            }
        }


    }

    @Scheduled(fixedRate = 1000 * 60 * 12)
    public  void  clearTokenByOutTime(){
        LOGGER.info("清除所有有效期内的token......");
        //清楚token信息
        List<String>  clearTokenLists=new ArrayList<String>();
        for(Map.Entry<String, SysUserToken> entry:tokenMap.entrySet()){
            System.out.println(entry.getKey()+"--->"+entry.getValue());
            if(entry.getValue().getOuttime().getTime()< new Date().getTime() ){
                principalMap.remove(entry.getValue().getUserid()); //清除无效的对应的用户登录状态
                clearTokenLists.add(entry.getKey());
            }
        }
        for(String token:clearTokenLists){
            tokenMap.remove(token);
        }
    }

    public  static void clearToken(String token){
        SysUserToken sysUserToken=tokenMap.get(token);
        tokenMap.remove(token);
        if(sysUserToken!=null) {
            principalMap.remove(sysUserToken.getUserid());
        }
    }

    /***
     * <p>获取用户token</p>
     * @param token
     * @return
     */
    public static SysUserToken getTokenByToken(String token){
        //获取用户token
        SysUserToken sysUserToken=tokenMap.get(token);
        if(sysUserToken!=null){
            //判断token是否过期  过期则清楚
            if(sysUserToken.getOuttime().getTime()< new Date().getTime() ){
                tokenMap.remove(token);
                return null;
            }
            return sysUserToken;
        }
        return null;
    }

    /***
     * <p>通过token获取用户登录状态</p>
     * @param token
     * @return
     */
    public static Principal getUserPrincipal(String token){
        //获取用户token
        SysUserToken sysUserToken=tokenMap.get(token);
        System.out.println("token="+token);
        if(sysUserToken!=null) {
            //判断token是否过期  过期则清除
            if (sysUserToken.getOuttime().getTime() < new Date().getTime()) {
                tokenMap.remove(token);
                principalMap.remove(sysUserToken.getUserid());
                return null;
            }
            Principal principal=principalMap.get(sysUserToken.getUserid());
            if(principal!=null){
                System.out.println("principal="+ principal.getUserid());
                return principal;
            }
        }

        return null;
    }

    /**
     * <p>增加用户token</p>
     * @param token
     * @param sysUserToken
     * @return
     */
    public  static SysUserToken addUserToken(String token ,SysUserToken sysUserToken){
            tokenMap.put(token,sysUserToken);
        return sysUserToken;
    }

    /***
     * <p>增加用户登录权限和登录状态</p>
     * @param token
     * @param sysUserToken
     * @param principal
     * @return
     */
    public  static SysUserToken addUserToken(String token ,SysUserToken sysUserToken,Principal principal){
        tokenMap.put(token,sysUserToken);
        addUserPrincipal(token,principal);
        return sysUserToken;
    }




    /***
     * <p>通过token增加用户登录状态</p>
     * @param token
     * @return
     */
    public static Principal addUserPrincipal(String token,Principal principal){
        //获取用户token
        SysUserToken sysUserToken=tokenMap.get(token);
        if(sysUserToken!=null) {
            //判断token是否过期  过期则清除
            if (sysUserToken.getOuttime().getTime() < new Date().getTime()) {
                tokenMap.remove(token);
                principalMap.remove(sysUserToken.getUserid());
                return null;
            }
            principalMap.put(sysUserToken.getUserid(),principal);
            return principal;
        }

        return null;
    }


}
